package xyf.p11.other.twopointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: P0015_ThreeNumberSum
 * Description:
 * Author: xyf
 * Date: 9/9/22 10:21 AM
 * Version: 1.0
 **/
public class P0015_ThreeNumberSum
{
    public List<List<Integer>> threeSum(int[] nums)
    {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length; i++)
        {
            int cur = nums[i];
            if (i > 0 && nums[i] == nums[i - 1])
            {
                continue;
            }

            int start = i + 1;
            int end = nums.length - 1;
            while (start < end)
            {
                if (start > i + 1 && nums[start] == nums[start - 1])
                {
                    start++;
                    continue;
                }
                if (end < nums.length - 1 && nums[end] == nums[end + 1])
                {
                    end--;
                    continue;
                }

                int sum = nums[start] + nums[end];
                if (sum == -cur)
                {
                    res.add(Arrays.asList(nums[i], nums[start], nums[end]));
                    start++;
                    end--;
                }
                else if (sum < -cur)
                {
                    start++;
                }
                else
                {
                    end--;
                }
            }
        }
        return res;
    }
}